package com.example.qqdbanner.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.example.qqdbanner.R;

import java.util.List;

/**
 * author : joker.peng
 * e-mail : joker@superxr.com
 * date   : 2024/8/3 21:51
 * desc   :
 */
public class InfiniteImagePagerAdapter extends PagerAdapter {
    private Context context;
    private List<String> imagePaths;
    private LayoutInflater inflater;

    public InfiniteImagePagerAdapter(Context context, List<String> imagePaths) {
        this.context = context;
        this.imagePaths = imagePaths;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE; // 返回一个很大的值实现无限轮播
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = inflater.inflate(R.layout.image_view, container, false);
        ImageView imageView = view.findViewById(R.id.iv);

        // 加载图片
        int actualPosition = position % imagePaths.size();
        String imagePath = imagePaths.get(actualPosition);
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        imageView.setImageBitmap(bitmap);

        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    public int getInitialPosition() {
        return Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % imagePaths.size(); // 设置初始位置
    }
}
